<?php
declare (strict_types=1);

namespace app\admin\controller;

use think\facade\View;
use think\response\Json;
use addons\Builder\facade\Builder;

class Role extends Base
{

    protected string $pk = 'id';

    protected string $model = '\app\common\model\Role';

    protected string $validate = 'Role';

    protected array $hasOne;

    public function index(): string
    {
        return Builder::Table()
            ->autoStructure($this->model, $this->pk, 'barDemo,230', false, false)
            ->addTopButtons(['add' => ['size' => '50%']])
            ->addRightButtons([
                'give'    => [
                    'title' => '分配权限',
                    'url'   => url('role/give')->build(),
                    'event' => '_openDrawer',
                    'size'  => '40%',
                    'site'  => 'r'
                ], 'edit' => ['size' => '50%'], 'delete'])
            ->addSearch([
                ['title', '角色名', 'input,Like']
            ])
            ->addExtraHtml(['role'])
            ->fetch();
    }

    /**
     * @param $id
     * @return string|Json
     */
    public function give($id)
    {
        if ($this->request->isAjax()) {
            try {
                $param = $this->request->post();
                $param['rules'] = $param['rules'] ? implode(',', $param['rules']) : '';
                $this->model::update($param);
                return json(['code' => 1, 'msg' => '操作成功']);
            } catch (\Exception $e) {
                return json(['code' => -1, 'msg' => $e->getMessage()]);
            }
        }

        extract((new \app\common\model\Menu())->getAuth($id));

        function childrenFun($item, $rule)
        {
            $children = [];
            foreach ($item['child'] as $child) {
                $children[] = [
                    'id'       => $child['id'],
                    'title'    => $child['title'],
                    'spread'   => true,
                    'children' => childrenFun($child, $rule),
                    'checked'  => in_array($child['id'], $rule)
                ];
            }
            return $children;
        }

        $list = [];
        foreach ($menu as $item) {
            $data = [
                'id'       => $item['id'],
                'title'    => $item['title'],
                'spread'   => true,
                'children' => childrenFun($item, $rule),
                'checked'  => in_array($item['id'], $rule)
            ];
            $list[] = $data;
        }
        return View::assign('list', $list)->fetch();
    }
}
